<?php

namespace app\customer\logic;
use app\admin\logic\TestLogic;
use app\common\library\Upload;
use app\common\service\UploadService;
use app\data\util\MqQueueName;
use app\shop\model\ShopsModel;
use app\systems\logic\MqTaskPushLogic;
use think\facade\Config;
use think\facade\Db;
use app\data\util\HttpUtil;
use app\common\library\RedissLock;

class TikMessageLogic extends BasicLogic
{
   /**
    * @desc 创建会话消息
    * @author luckyXiong
    * @date  2024-03-22
    */
   public function create_conversations($params){
       htmlLog(['data'=>$params],OPERATE_LOG . date('Ym') . '/create_conversations/' . date('Ymd') . '.txt');
       $order_id = getIsset($params,'order_id');
       $shop_id  = getIsset($params,'shop_id');
       $type     = getIsset($params,'type');
       $text     = getIsset($params,'text');

      $redis_lock = new RedissLock();
      $key        = 'create_conversations::'.$order_id;
      $lock       = $redis_lock::lock($key, $redis_lock::UNBLOCK, 500);
      if (!$lock){
          return  ['code'=>201,'msg'=>'创建数据并发了'];
       }

       // update 2024-05-17 会话重复创建
       $buyer_user_id  = self::get_order_info($order_id);

       if(!$buyer_user_id)  return ['code'=>201,'msg'=>'暂无用户ID信息'];
       $buyer_order_id = md5($buyer_user_id.$order_id);
       $exist_info     = Db::name('conversations')->where('buyer_order_id',$buyer_order_id)->find();
       $account        = Db::name('shops')->where('id',$shop_id)->field('id as shop_id,app_secret,app_key,cipher,access_token')->find();

       if($exist_info){
           $conversation_id = $exist_info['conversation_id'];
       }else{
           $tik_info        = Config::get('Logisticskey.' . 'TIKTOK');
           $path            = $tik_info['create_conversations_path'];
           $basic_url       = $tik_info['basic_url'];
           $sign            = $account['app_secret'] . '' . $path . 'app_key' . $account['app_key'] . 'shop_cipher' . $account['cipher'] . 'timestamp' . time() . '{"buyer_user_id":"' . $buyer_user_id . '"}' . $account['app_secret'];
           $sign            = hash_hmac('sha256', $sign, $account['app_secret']);
           $url             = $basic_url . $path . "?app_key=" . $account['app_key'] . "&shop_cipher=" . $account['cipher'] . "&sign=" . $sign . "&timestamp=" . time();
           $return          = HttpUtil::tikPostUrl($url, ['buyer_user_id'=>$buyer_user_id], $account['access_token']);
           $conversation_id = $return['data']['conversation_id']??'';
           if(!$conversation_id){
               //记录错误日志;
               htmlLog(['url'=>$url,'buyer_user_id'=>$buyer_user_id,'result'=>$return],OPERATE_LOG . date('Ym') . '/create_conversations_fail/' . date('Ymd') . '.txt');
           }
           $insert_info = [
               'shop_id'        =>$shop_id,
               'order_id'       =>$order_id,
               'buyer_user_id'  =>$buyer_user_id,
               'conversation_id'=>$conversation_id,
               'buyer_order_id' =>$buyer_order_id,
               'created_time'   =>date("Y-m-d H:i:s", time()),
           ];
           Db::name('conversations')->insert($insert_info);
       }

       //2024-05-24 查看是否发送过消息;
       $exist_message = Db::name('conversations_info')->where(['conversation_id'=>$conversation_id,'order_id'=>$order_id,'type'=>$type])->find();
       if($exist_message)    return  ['code'=>201,'msg'=>'已发送过此类型消息'];

       //发送消息
       self::send_message($conversation_id,$account,$type,$order_id,$text);
       $lock->unlock();
       return  true;
   }


    /**
     * 发送站内信 2024-05-08
     * @param array conversation_id 会话id
     * @param array type 类型
     * @param array content 内容
     */
    public function send_message($conversation_id,$account,$type,$order_id,$text)
    {
        if(!$conversation_id) return ['code'=>201,'msg'=>'暂无conversation_id信息'];
        if($type=='3'){
            $content['content'] = $text;
        }else{
            $content['content'] = self::message_template($account['shop_id'],$type);
        }
        $content_info       = $content['content'];
        $types              = "TEXT";
        $content            = json_encode($content,true);
        $contents           = json_encode($content,true);
        $tik_info           = Config::get('Logisticskey.' . 'TIKTOK');
        $path               = $tik_info['create_conversations_path'];
        $path               = $path .'/'.$conversation_id . '/messages';
        $sign               = $account['app_secret'] . '' . $path . 'app_key' . $account['app_key'] . 'shop_cipher' . $account['cipher'] . 'timestamp' . time() . '{"type":"' . $types . '","content":' . $contents . '}' . $account['app_secret'];
        $sign               = hash_hmac('sha256', $sign, $account['app_secret']);
        $basic_url          = $tik_info['basic_url'];
        $url                = $basic_url . $path . "?app_key=" . $account['app_key'] . "&shop_cipher=" . $account['cipher'] . "&sign=" . $sign . "&timestamp=" . time();
        $return             = HttpUtil::tikPostUrl($url, ['type'=>$types,'content'=>$content], $account['access_token']);
        $message_id         = $return['data']['message_id']??'';

        if(empty($message_id)){
            //记录错误日志;
            htmlLog(['result'=>$return,'conversation_id'=>$conversation_id,'order_id'=>$order_id],OPERATE_LOG . date('Ym') . '/send_message/' . date('Ymd') . '.txt');
        }

        $insert_info = [
                'conversation_id'        =>$conversation_id,
                'shop_id'                =>$account['shop_id'],
                'order_id'               =>$order_id,
                'message_id'             =>$message_id,
                'type'                   =>$type,
                'content'                =>$content_info,
                'created_time'           =>date("Y-m-d H:i:s", time()),
        ];
        Db::name('conversations_info')->insert($insert_info);

        if($type=='3'){ //私信信息 ba_im_batch_conversations
            $batch_conversations_info =  Db::name('im_batch_conversations')->where('order_id',$order_id)->field('id,buyer_user_id')->find();
            if($batch_conversations_info){
                $batch_conversations_log = [
                    'batch_id'       =>$batch_conversations_info['id'],
                    'shop_id'        =>$account['shop_id'],
                    'conversation_id'=>$conversation_id,
                    'order_id'       =>$order_id,
                    'buyer_user_id'  =>$batch_conversations_info['buyer_user_id'],
                    'content'        =>$text,
                    'created_time'   =>date("Y-m-d H:i:s", time()),
                ];
                Db::name('im_batch_conversations_log')->insert($batch_conversations_log);
                Db::name('im_batch_conversations')->where('id',$batch_conversations_info['id'])->update(['conversation_id'=>$conversation_id,'send_status'=>2]);
            }
        }
    }




    /**
     * 发送txt消息 2024-05-20
     * @param array conversation_id 会话id
     * @param array type 类型
     * @param array content 内容
     */
    public function send_message_txt($conversation_id,$shop_id,$order_id,$txt='',$send_type=1)
    {
        $content['content'] = $txt;
        $content_info       = $content['content'];
        $types              = "TEXT";
        $content            = json_encode($content,true);
        $contents           = json_encode($content,true);
        $tik_info           = Config::get('Logisticskey.' . 'TIKTOK');
        $path               = $tik_info['create_conversations_path'];
        $path               = $path .'/'.$conversation_id . '/messages';
        $account            = Db::name('shops')->where('id',$shop_id)->field('id as shop_id,app_secret,app_key,cipher,access_token')->find();
        $sign               = $account['app_secret'] . '' . $path . 'app_key' . $account['app_key'] . 'shop_cipher' . $account['cipher'] . 'timestamp' . time() . '{"type":"' . $types . '","content":' . $contents . '}' . $account['app_secret'];
        $sign               = hash_hmac('sha256', $sign, $account['app_secret']);
        $basic_url          = $tik_info['basic_url'];
        $url                = $basic_url . $path . "?app_key=" . $account['app_key'] . "&shop_cipher=" . $account['cipher'] . "&sign=" . $sign . "&timestamp=" . time();
        $return             = HttpUtil::tikPostUrl($url, ['type'=>$types,'content'=>$content], $account['access_token']);
        $message_id         = $return['data']['message_id']??'';
        $insert_info = [
            'conversation_id'        =>$conversation_id,
            'shop_id'                =>$account['shop_id'],
            'order_id'               =>$order_id,
            'message_id'             =>$message_id ?:json_encode($return),
            'type'                   =>1,
            'content'                =>$content_info,
            'created_time'           =>date("Y-m-d H:i:s", time()),
        ];
        Db::name('im_send_conversations_info')->insert($insert_info);
        $shop_info  = Db::name('im_conversations')->where('shop_id',$shop_id)
            ->field('customer_nickname,customer_avatar,customer_role,customer_im_id')
            ->find();
        if($message_id){
            $insert_arr = [
                'shop_id'          => $shop_id,
                'conversation_id'  => $conversation_id,
                'order_id'         => $order_id,
                'content'          => $txt,
                'message_id'       => $message_id,
                'message_nickname' => $shop_info['customer_nickname']??'',
                'message_avatar'   => $shop_info['customer_avatar']??'',
                'message_role'     => $shop_info['customer_role']??'',
                'message_im_id'    => $shop_info['customer_im_id']??'',
                'conversations_message_id' => md5($conversation_id.$message_id),
                'message_type'             => 1,
                'timestamp'                => time(),
                'created_time'             => date("Y-m-d H:i:s", time()),
            ];
            Db::name('im_conversations_message')->insert($insert_arr);
            $update_conversations['message_content']      = $txt;
            $update_conversations['created_time']         = date("Y-m-d H:i:s", time());
            $update_conversations['conversations_reply']  = 2;
            Db::name('im_conversations')->where('conversation_id',$conversation_id)->update(
                $update_conversations
            );
        }
      
    }





    /**
     * @param $account
     * @param $type
     * @return string
     * @desc 获取模版消息
     */
    public function message_template($shop_id,$type='')
    {
        $message = "";
        $conversations_shop =Db::name('conversations_shop')->where('shop_id',$shop_id)->find();
        $conversations_shop =objectToArray($conversations_shop);
        if($type==1){
            $message = $conversations_shop['checkout_letter']??''; //下单发货
        }
        if($type==2){ //status = 'DELIVERED'
            $message = $conversations_shop['reply_letter']??''; //签收
        }
        return $message;
    }




    /**
     * @desc 获取店铺消息模版
     * @date 2024-04-28
     * @author luckyXiong
     */
    public function get_shop_message($params=[]){
        $shop_id = $params['shop_id']??'';
        $limit  = $params['limit']??'10';
        $where   = [];
        if($shop_id){
            $where[] = ['shop_id','=',$shop_id];
        }

        $res = Db::name('conversations_shop')
            ->where($where)
            ->paginate($limit);
        $list =   $res->items();
        $list =  objectToArray($list);

        $operate= array_column($list,'operator');

        $operate_names = Db::name('admin')->whereIn('id',$operate)->field('id,nickname')->select()->toArray();

        $operate_names_map = array_column($operate_names,null,'id');

        foreach($list as $k=>$v){
            $operate_names = $operate_names_map[$v['operator']]??[];
            $list[$k]['operate_name'] = $operate_names['nickname']??'';
        }
        $data = [
            'list'   => $list,
            'total'  => $res->total(),
        ];
        return json(DefaultResponse(200, true, '操作成功!', $data));
    }



    /**
     * @desc 获取店铺消息模版
     * @date 2024-04-28
     * @author luckyXiong
     */
    public function updateShopInfo($params=[]){
        $checkout_letter = $params['checkout_letter']??'';
        $reply_letter    = $params['reply_letter']??'';
        $batch_letter    = $params['batch_letter']??'';
        $id              = $params['id']??'';
        Db::name('conversations_shop')->where('id',$id)->update(
            [
                'checkout_letter'=>$checkout_letter,
                'reply_letter'=>$reply_letter,
            ]);
        return json(DefaultResponse(200, true, '操作成功!', null));
    }


   /**
    * 获取订单详情数据
    */
   public function get_order_info($order_id=''){
        if(!$order_id)  return '';
        return  Db::name('order_append')->where('order_id',$order_id)->value('user_id');

   }


    /**
     * @desc 获取会话消息列表
     * @date 2024-04-29
     * @author luckyXiong
     */
   public function get_conversation_list($params=[]){

       $shop_id     = $params['shop_id']??'';
       $sender_role = $params['sender_role']??'';
       $orderId     = $params['order_id']??'';
       $limit       = $params['limit']??'10';
       $where       = [];

       if($shop_id){
           $where[] = ['shop_id','=',$shop_id];
       }

       if($sender_role){
           $where[] = ['message_role','=',$sender_role];
       }

       if ($orderId) {
           $order_ids = trim($orderId);
           $order_ids = array_filter(array_map('trim', explode("\n", $order_ids)));
           if (!empty($order_ids)) {
               $where[] = ['order_id', 'in', $order_ids];
           }
       }


       $field = ['id,shop_id,conversation_id,order_id,content,message_id,message_im_id as sender_im_id,
                 message_role as sender_role,message_nickname as sender_nickname,message_avatar as sender_avatar,
                 message_type as sender_mess_type,created_time as createtime'
           ];

       $res = Db::name('im_conversations_message')
           ->where($where)
           ->field($field)
           ->order('timestamp desc')
           ->paginate($limit);

       $list =   $res->items()?:[];

       $list =  objectToArray($list);

       //批量获取店铺信息及sku数量信息;
       $shop_ids      = array_column($list,'shop_id');
       $shopInfos     = Db::name('shops')->whereIn('id',$shop_ids)->field('name,id')->select();
       $shopInfos     = objectToArray($shopInfos);
       $shopInfos_map = array_column($shopInfos,null,'id');

       $message_type  = ['1'=>'文本消息',2=>'通知消息',3=>'其他消息'];

       foreach($list as $k=>$v){
           $shop_name  = $shopInfos_map[$v['shop_id']]??[];
           $list[$k]['shop_name']    = $shop_name['name']??'';
           $list[$k]['is_visible']   = 1;
           if($v['sender_role']=='SHOP'){
               $list[$k]['sender_role'] = 'CUSTOMER_SERVICE';
           }
           $list[$k]['content']      = str_replace(array("\r", "\n"), '', $v['content']);
           $list[$k]['message_type'] = $message_type[$v['sender_mess_type']]??'';
       }

       $data = [
           'list'   => $list,
           'total'  => $res->total(),
       ];
       return json(DefaultResponse(200, true, '操作成功!', $data));
   }




    /**
     * @desc  消息会话IM
     * @date   2024-05-20
     * @author luckyXiong
     */
    public function get_im_list($params=[]){
        $orderId        = $params['order_id']??'';
        $unread_count   = $params['unread_count']??'';
        $limit          = $params['limit']??'20';
        $where          = [];

        if($orderId){
            $where[] = ['order_id','=',$orderId];
        }

        //已读传1 未读:传2
        if($unread_count == 1){
            $where[]  = ['conversations_unread_count','=',0];
        }

        if($unread_count == 2){
            $where[]  = ['conversations_unread_count','<>',0];
        }

        
        $where[] = ['im_status','=',1];


        $res = Db::name('im_conversations')
            ->where($where)
            ->order('created_time desc')
            ->paginate($limit);

        $list =   $res->items()?:[];

        foreach($list as $k=>$v){
            $list[$k]['message_content'] = str_replace(array("\r", "\n"), '', $v['message_content']);
        }

        $list =  objectToArray($list);


        return [
            'list'   => $list,
            'total'  => $res->total(),
        ];

    }


    /**
     * @desc 本地数据上传OSS
     * @author luckyXiong
     * @Date   2024/05/20 10:55
     */
    public function uploadImages($params=[]){
        $file          = $params['file']??'';
        $upload_result = (new upload($file))->upload(null);
        $doc_url       = $upload_result['full_url']??'';
        //地址上传到阿里云OSS;
        $service   = new UploadService();
        $BASE_PATH = dirname(__DIR__, 1);
        $local_dir = $BASE_PATH . '/runtime/images/';
        if (!is_dir($local_dir)) {
            mkdir($local_dir ,0777 ,true);
        }
        //存入本地地址;
        $local_dir_file = $local_dir.time().'.png';
        file_put_contents($local_dir_file, file_get_contents($doc_url));

        //上传阿里云地址;
        $ossDir   = 'images/' .date('ymd').'/'.time().'.png';
        $res      = $service->uploads($local_dir_file,$ossDir);
        //上传后清除本地数据
        unlink($local_dir_file);
        return $res['info']['url']??'';
    }


    /**
     * @desc   消息会话IM详情
     * @date   2024-05-20
     * @author luckyXiong
     */
    public function get_im_info($params=[]){
        $conversation_id  = $params['conversation_id']??'';
        $order_id         = $params['order_id']??'';
        $limit            = $params['limit']??'10';
        $res              = Db::name('im_conversations_message')->where(['conversation_id'=>$conversation_id,'order_id'=>$order_id])
                           ->order('timestamp desc')
                           ->paginate($limit);
        $list            =   $res->items()?:[];

        return [
            'list'   => $list,
            'total'  => $res->total(),
        ];
    }


    /**
     * @desc   发送文本消息
     * @date   2024-05-20
     * @author luckyXiong
     */
    public function sendText($params=[]){
        $conversation_id = $params['conversation_id']??'';
        $shop_id         = $params['shop_id']??'';
        $order_id        = $params['order_id']??'';
        $txt             = $params['txt']??'';
        $send_type       = 1;
        $this->send_message_txt($conversation_id,$shop_id,$order_id,$txt,$send_type);
    }


    /**
     * @desc   发送文本消息
     * @date   2024-05-20
     * @author luckyXiong
     */
    public function sendImage($params=[]){
        $conversation_id = $params['conversation_id']??'';
        $shop_id         = $params['shop_id']??'';
        $order_id        = $params['order_id']??'';
        $url             = $params['url']??'';
        $content         = $params['content']??'';
        return $this->send_message_image($conversation_id,$shop_id,$order_id,$url,$content);
    }



    /**
     * @desc   消息变更为已读
     * @author xx
     * @date   2024-05-19
     */
    public function messages_read_operate($params=[]){
       $conversation_id = $params['conversation_id']??'';
       $shop_id         = $params['shop_id']??'';
       $res =  $this->messages_read($params);
       if($res['code']==0 || $res['message']=='Success'){
           //更新主表数据;
           Db::name('im_conversations')->where(['shop_id'=>$shop_id,'conversation_id'=>$conversation_id])->update(['conversations_unread_count'=>0]);
       }
    }



    /**
     * @desc   消息标记为已读
     * @author xx
     * @date   2024-05-19
     */
    public function messages_read($params=[]){
        $conversation_id = $params['conversation_id']??'';
        $shop_id         = $params['shop_id']??'';
        $account         = Db::name('shops')->where('id',$shop_id)->field('id as shop_id,app_secret,app_key,cipher,access_token')->find();
        $path            = Config('Logisticskey.TIKTOK.create_conversations_path').'/'.$conversation_id.'/messages/read';
        $base_url        = Config('Logisticskey.TIKTOK.basic_url');
        $sign            = $account['app_secret'] . '' . $path . 'app_key' . $account['app_key'] . 'shop_cipher' . $account['cipher'] . 'timestamp' . time() . '{"conversation_id":"' . $conversation_id . '"}' . $account['app_secret'];
        $sign            = hash_hmac('sha256', $sign, $account['app_secret']);
        $url             = $base_url . $path . "?app_key=" . $account['app_key'] . "&shop_cipher=" . $account['cipher'] . "&sign=" . $sign . "&timestamp=" . time();
        return HttpUtil::tikPostUrl($url, ['conversation_id'=>$conversation_id], $account['access_token']);
    }


    /**
     * @desc   消息标记为已读
     * @author xx
     * @date   2024-05-20
     */
    public function send_message_image($conversation_id,$shop_id,$order_id,$image_url,$image_content){
        $content            = [
            'url'     => $image_url,
             'width'  => 300,
             'height' => 300
        ];
        $types              = "IMAGE";
        $content            = json_encode($content,true);
        $contents           = json_encode($content,true);
        $tik_info           = Config::get('Logisticskey.' . 'TIKTOK');
        $path               = $tik_info['create_conversations_path'];
        $path               = $path .'/'.$conversation_id . '/messages';
        $account            = Db::name('shops')->where('id',$shop_id)->field('id as shop_id,app_secret,app_key,cipher,access_token')->find();
        $sign               = $account['app_secret'] . '' . $path . 'app_key' . $account['app_key'] . 'shop_cipher' . $account['cipher'] . 'timestamp' . time() . '{"type":"' . $types . '","content":' . $contents . '}' . $account['app_secret'];
        $sign               = hash_hmac('sha256', $sign, $account['app_secret']);
        $basic_url          = $tik_info['basic_url'];
        $url                = $basic_url . $path . "?app_key=" . $account['app_key'] . "&shop_cipher=" . $account['cipher'] . "&sign=" . $sign . "&timestamp=" . time();
        $return             = HttpUtil::tikPostUrl($url,['type'=>$types,'content'=>$content], $account['access_token']);
        $message_id         = $return['data']['message_id']??'';
        $insert_info = [
            'conversation_id'        =>$conversation_id,
            'shop_id'                =>$account['shop_id'],
            'order_id'               =>$order_id,
            'message_id'             =>$message_id ?:json_encode($return),
            'type'                   =>2,
            'content'                =>$image_url,
            'created_time'           =>date("Y-m-d H:i:s", time()),
        ];
        Db::name('im_send_conversations_info')->insert($insert_info);
        $shop_info  = Db::name('im_conversations')->where('shop_id',$shop_id)
            ->field('customer_nickname,customer_avatar,customer_role,customer_im_id')
            ->find();
        if($message_id){
            $insert_arr = [
                'shop_id'          => $shop_id,
                'conversation_id'  => $conversation_id,
                'order_id'         => $order_id,
                'content'          => $image_content,
                'message_id'       => $message_id,
                'message_nickname' => $shop_info['customer_nickname']??'',
                'message_avatar'   => $shop_info['customer_avatar']??'',
                'message_role'     => $shop_info['customer_role']??'',
                'message_im_id'    => $shop_info['customer_im_id']??'',
                'conversations_message_id' => md5($conversation_id.$message_id),
                'message_type'             => 2,
                'timestamp'                => time(),
                'created_time'             => date("Y-m-d H:i:s", time()),
            ];
            Db::name('im_conversations_message')->insert($insert_arr);
            Db::name('im_conversations')->where('conversation_id',$conversation_id)->update(
                ['message_content'=>$url,'conversations_reply'=>2,'created_time'=>date("Y-m-d H:i:s", time())]
            );
        }

    }


    /**
     * @desc   群发消息列表
     * @author xx
     * @date   2024-05-20
     */
    public function get_batch_messages($params=[]){

        $shop_id            = $params['shop_id']??'';
        $conversations_time = $params['conversations_time']??'';
        $limit              = $params['limit']??'10';
        $where              = [];

        if($shop_id){
            $where[] = ['shop_id','=',$shop_id];
        }


        if ($conversations_time) {
            $conversations_time = explode(',', $conversations_time);
            $where[] = ['timestamp', '>=', strtotime($conversations_time[0])];
            $where[] = ['timestamp', '<=', strtotime($conversations_time[1])];
        }

        $res = Db::name('im_conversations')
            ->order('timestamp desc')
            ->where($where)
            ->paginate($limit);

        $list =   $res->items()?:[];
        $list =   objectToArray($list);

        //批量获取店铺信息及sku数量信息;
        $shop_ids      = array_column($list,'shop_id');
        $shopInfos     = Db::name('shops')->whereIn('id',$shop_ids)->field('name,id')->select();
        $shopInfos     = objectToArray($shopInfos);
        $shopInfos_map = array_column($shopInfos,null,'id');

        //批量获取消息群发模版;
        $shopConversations     = Db::name('conversations_shop')->whereIn('id',$shop_ids)->field('batch_letter,shop_id')->select();
        $shopConversations     = objectToArray($shopConversations);
        $shopConversations_map = array_column($shopConversations,null,'shop_id');



        foreach($list as $k=>$v){
            $shop_name    = $shopInfos_map[$v['shop_id']]??[];
            $shop_letter  = $shopConversations_map[$v['shop_id']]??[];
            $list[$k]['shop_name']            = $shop_name['name']??'';
            $letter      = $shop_letter['batch_letter']??'';
            $list[$k]['message_content']      = str_replace(array("\r", "\n"), '', $letter);
            $list[$k]['conversations_time']   = date("Y-m-d H:i:s", $v['timestamp']);
            $list[$k]['batch_send_time']      = $v['batch_send_time'] ? date("Y-m-d H:i:s", $v['batch_send_time']) : '';
        }

        return [
            'list'   => $list,
            'total'  => $res->total(),
        ];
    }


    /**
     * @desc   群发消息操作
     * @author xx
     * @date   2024-05-20
     */
    public function batch_send_messages($params=[]){
        $ids  =  $params['ids'];
        $ids  =  is_array($ids) ?  $ids : explode(',', $ids);
        if(!$ids)   return  '请选择发送数据!';
        $list =  Db::name('im_conversations')->whereIn('id',$ids)
                 ->field('shop_id,order_id,conversation_id')
                 ->select();

        $list = objectToArray($list);
        $shop_ids = array_column($list,'shop_id');
        $shop_ids = array_values(array_unique($shop_ids));
        $letter   = Db::name('conversations_shop')->whereIn('shop_id',$shop_ids)->field('shop_id,batch_letter')->select()->toArray();
        $letter   = objectToArray($letter);
        $letter_map = array_column($letter,null,'shop_id');
        if($list){
            foreach($list as $v){
                $letter_info = $letter_map[$v['shop_id']]??[];
                $text        = $letter_info['batch_letter']??'';
                if(!$text) continue;
                //数据推送到队列处理
                MqTaskPushLogic::mq_task_push(
                    '',
                    MqQueueName::QUEUE_TIK_SEND_CONVERSATION_MESSAGE_QUEUE,
                    [
                        'shop_id'        =>$v['shop_id'],
                        'order_id'       =>$v['order_id'],
                        'conversation_id'=>$v['conversation_id'],
                        'send_type'      =>2,
                        'txt'            =>str_replace(array("\r", "\n"), '', $text),
                    ],
                    false
                );
            }
        }
    }


    /**
     * @desc   群发消息操作MQ
     * @author xx
     * @date   2024-05-21
     */
    public function send_batch_messages($params=[]){
        htmlLog(['data'=>$params],OPERATE_LOG . date('Ym') . '/send_batch_messages/' . date('Ymd') . '.txt');
        $conversation_id = $params['conversation_id']??'';
        $shop_id         = $params['shop_id']??'';
        $order_id        = $params['order_id']??'';
        $txt             = $params['txt']??'';
        $send_type       = $params['send_type']??'';
        self::send_message_txt($conversation_id,$shop_id,$order_id,$txt,$send_type);
        return  true;
    }



    /**
     * @desc   获取订单详情数据sku
     * @author xx
     * @date   2024-05-29  getTrackInfo
     */
    public function getSkuInfo($params=[]){
           $order_id  =  $params['order_id']??'';
           $field     =  'id,order_id,product_name,seller_sku,sku_name,createtime,sku_image,sale_price';
           $info      =  Db::name('im_order_info')->field($field)->where('order_id',$order_id)->select();
           $info      =  objectToArray($info);
           $order_info=   Db::name('order')->where('order_id',$order_id)->field('status,createtime')->find();
           $list      =  [
               'order_info'=>[],
               'order_sku' =>[],
           ];
           if(count($info)>1){
                 $total_price        = array_column($info,'sale_price');
                 $total_price        = array_sum($total_price);
                 $list['order_info'] = [
                     'order_id'      => $order_id,
                     'order_status'  => $order_info['status']??'',
                     'createtime'    => $order_info['createtime']??'',
                     'total_price'   => $total_price,
                     ];
                 $list['order_sku'] = $info;
           }else{
               $total_price        = $info[0]['sale_price']??'';
               $list['order_info'] = [
                   'order_id'      => $order_id,
                   'order_status'  => $order_info['status']??'',
                   'createtime'    => $order_info['createtime']??'',
                   'total_price'   => $total_price,
               ];
               $list['order_sku']  = $info;
           }
           return  $list;
    }



    /**
     * @desc   获取订单track
     * @author xx
     * @date   2024-05-29
     */
    public function getTrackInfo($params=[]){
        $order_id  =  $params['order_id']??'';
        $info      =  Db::name('order_track')
                      ->where('order_id',$order_id)
                      ->field('tracking_number,time_iso,location')
                      ->order('time_utc desc')
                      ->select()
                      ->toArray();
        $list      =  [
            'order_info'=>[],
            'track_info'=>[],
        ];

        $postal_code  = Db::name('order_append')->where('order_id',$order_id)->value('postal_code');
        $first_time   = Db::name('order')->where('order_id',$order_id)->value('createtime');
        $quantity     = Db::name('im_order_info')->where('order_id',$order_id)->field('id')->count();
        $track_number = $info[0]['tracking_number']??'';
        $list['order_info'] = [
            'delivery_date' => '--',
            'quantity'      => $quantity,
            'track_number'  => $track_number,
            'postal_code'   => $postal_code,
        ];

        foreach($info as $k=>$v){
            $info[$k]['createtime'] =self::change_date_time($v['time_iso']);
            $info[$k]['location']   ="Arrived at the ".$v['location'];
            unset($info[$k]['time_iso']);
            unset($info[$k]['tracking_number']);
        }
        $first_time = date('m/d/Y H:i:s', $first_time);
        $firstData = [
            'location'   => 'Order placed',
            'createtime' => $first_time
        ];
        array_push($info, $firstData);
        $list['track_info'] = $info;
        return  $list;

    }


    /**
     * @desc 时间格式转换
     * @date 2024-05-30
     */
    private function change_date_time($dateString=''){
        $timestamp         =  strtotime($dateString)-15*3600;
        $formattedDateTime =  date('m/d/Y H:i:s', $timestamp);
        return $formattedDateTime;
    }


    /**
     * @desc   tik面板回复消息的变更为已读
     * @author xx
     * @date   2024-05-31
     */
    public function change_message_read(){
        $field   = ['id,shop_id,conversation_id,order_id'];
        $where   = [];
        $where[] = ['conversations_unread_count','>',0];
        $where[] = ['im_status','>',0];
        $list    = Db::name('im_conversations')
            ->where($where)
            ->field($field)
            ->order('timestamp asc')
            ->select();
        $list    = objectToArray($list);
        if(!$list)  return '暂无数据!';
        //队列处理数据
        foreach($list as $v){
            //数据推送到队列处理
            MqTaskPushLogic::mq_task_push(
                '',
                MqQueueName::QUEUE_TIKTOK_ORDER_CONVERSATIONS_READ_QUEUE,
                [
                    'shop_id'        =>$v['shop_id'],
                    'order_id'       =>$v['order_id'],
                    'conversation_id'=>$v['conversation_id'],
                ],
                false
            );
        }
    }







}